/**
 * 转账流程状态
 */
export const state = () => {
  let account = sessionStorage.getItem("elsepay-account")||'';
  let remark = sessionStorage.getItem("elsepay-remark")||'';
  let userInfo = sessionStorage.getItem("elsepay-user-info");
  let form = sessionStorage.getItem("elsepay-form");
  let status = sessionStorage.getItem("elsepay-status");

  try {
    userInfo = JSON.parse(userInfo);
  } catch (e) {
    userInfo = null;
  }

  try {
    form = JSON.parse(form);
  } catch (e) {
    form = null;
  }

  try {
    status = JSON.parse(status);
  } catch (e) {
    status = null;
  }
  return {
    status,
    remark,
    account,
    userInfo,
    form, //转账表单
  }
}

export const mutations = {
  setStatus(state, status) {
    if (status) {
      sessionStorage.setItem("elsepay-status", JSON.stringify(status));
    } else {
      sessionStorage.removeItem("elsepay-status");
    }
    state.status = status || null
  },
  setRemark(state, remark) {
    if (remark) {
      sessionStorage.setItem("elsepay-remark", remark);
    } else {
      sessionStorage.removeItem("elsepay-remark");
    }
    state.remark = remark || ''
  },
  setAccount(state, account) {
    if (account) {
      sessionStorage.setItem("elsepay-account", account);
    } else {
      sessionStorage.removeItem("elsepay-account");
    }
    state.account = account;
  },
  setUserInfo(state, user) {
    // 每次保存后缓存到本地
    if (user) {
      sessionStorage.setItem("elsepay-user-info", JSON.stringify(user));
    } else {
      sessionStorage.removeItem("elsepay-user-info");
    }
    state.userInfo = user || null
  },
  setForm(state, form) {
    if (form) {
      sessionStorage.setItem("elsepay-form", JSON.stringify(form));
    } else {
      sessionStorage.removeItem("elsepay-form");
    }
    state.form = form || null
  },
}

export const actions = {
  clear({
    commit
  }) { // 清楚所有状态
    commit('setStatus', null)
    commit('setAccount', '')
    commit('setRemark', '')
    commit('setUserInfo', null)
    commit('setForm', null)
  },

}
